package com.sskj.one.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hjq.toast.ToastUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.IAgentWebSettings;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.one.R;
import com.sskj.one.view.AndroidInterfaceWeb;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Hey
 * Create at  2019/05/30
 */
public class WebH5Activity extends BaseActivity<WebPresenter> {


    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.tvTitle)
    TextView tvTitle;

    private String title;
    private String weburl;
    private KProgressHUD progress;
    private boolean loadData;

    private AgentWeb agentWeb;

    @Override
    public int getLayoutId() {
        return R.layout.app_activity_h5web;
    }

    @Override
    public WebPresenter getPresenter() {
        return new WebPresenter();
    }

    @Override
    public void initView() {
        title = getIntent().getStringExtra("title");
        weburl = getIntent().getStringExtra("url");
        tvTitle.setText(title);
        loadData = getIntent().getBooleanExtra("loadData", false);
        agentWeb = AgentWeb.with(this)
                .setAgentWebParent(webView, new ViewGroup.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("");
//        agentWeb.getJsInterfaceHolder().addJavaObject("appclient", new AndroidInterface(agentWeb, this));
        init();
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                setLoadingView();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                if (progress != null) {
//                    progress.dismiss();
//                }
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("http://csonto.com")) {
//                    progress = null;
                    ARouter.getInstance().build(RConfig.APP_MAIN).navigation();
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }



    @Override
    public void initData() {
    }
    /**
     * 设置加载页面
     */
    private void setLoadingView() {
        progress = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("加载中")
                .setCancellable(true)
                .show();
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void init() {
        String url = weburl;
//        setLoadingView();
        //覆盖WebView默认通过第三方或者是系统浏览器打开网页的行为，使得网页可以在WebView中打开

        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new AndroidInterface(agentWeb,this), "appclient");
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

        //支持插件

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        if (loadData) {
            Log.e("url", url);
            agentWeb.getWebCreator().getWebView().loadData(url, "text/html", "utf-8");
        } else {
            agentWeb.getWebCreator().getWebView().loadUrl(url);
        }

    }

    public static void start(Context context, String title, String url, boolean loadData) {
        Intent intent = new Intent(context, WebH5Activity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("loadData", loadData);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
    public class AndroidInterface {
        private AgentWeb agent;
        private Context context;

        public AndroidInterface(AgentWeb agent, Context context) {
            this.agent = agent;
            this.context = context;
        }
        @JavascriptInterface
        public void clickAddImage() {
            Log.i("info", "clickAddImage: -------------------------------------------------------");
            ToastUtils.show("hello");
        }
    }
}
